import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:xiecheng_lvyou/dao/search_dao.dart';
import 'package:xiecheng_lvyou/model/search_model.dart';
import 'package:xiecheng_lvyou/pages/speak_page.dart';
import 'package:xiecheng_lvyou/util/navigator_util.dart';
import 'package:xiecheng_lvyou/widget/search_bar.dart';
import 'package:xiecheng_lvyou/widget/webview.dart';

const TYPES = ['food', 'shop', 'district'];

class SearchPage extends StatefulWidget {
  final bool? hideLeft;
  final String? searchUrl;
  final String? keyword;
  final String? hint;
  const SearchPage(
      {super.key,
      this.hideLeft = false,
      this.searchUrl,
      this.keyword,
      this.hint});
  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage>
    with AutomaticKeepAliveClientMixin {
  String? keyword;
  SearchModel? searchModel;

  @override
  bool get wantKeepAlive => true;
  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
        body: Column(
      children: [
        _appBar(),
        Expanded(
            flex: 1,
            child: MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: ListView.builder(
                    itemCount: searchModel?.data?.length ?? 0,
                    itemBuilder: (BuildContext content, int position) {
                      return _item(position);
                    })))
      ],
    ));
  }

  _onTextChange(String text) {
    keyword = text;
    if (text.isEmpty) {
      setState(() {
        searchModel = null;
      });
      return;
    }
    String url = '${widget.searchUrl ?? ''}$text';
    SearchDao.fetch(url, text).then((SearchModel model) {
      // 只有当前输入的内容和服务端返回的内容一致时才渲染
      if (model.keyword == keyword) {
        setState(() {
          searchModel = model;
        });
      }
    }).catchError((error) {});
  }

  _appBar() {
    return Column(
      children: [
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
                colors: [Color(0x66000000), Colors.transparent],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter),
          ),
          child: Container(
              padding: const EdgeInsets.only(top: 30),
              height: 80,
              decoration: const BoxDecoration(color: Colors.white),
              child: SearchBarNav(
                hideLeft: widget.hideLeft,
                defaultText: widget.keyword,
                hint: widget.hint,
                speakClick: _jumpToSpeak,
                leftButtonClick: () {
                  Navigator.pop(context);
                },
                onChanged: _onTextChange,
              )),
        ),
      ],
    );
  }

  _item(int position) {
    if (searchModel == null || searchModel!.data == null) return null;
    SearchItem item = searchModel!.data![position];
    return GestureDetector(
      onTap: () {
        NavigatorUtil.push(context, WebView(url: item.url, title: '详情'));
      },
      child: Container(
        padding: const EdgeInsets.all(10),
        decoration: const BoxDecoration(
            border: Border(bottom: BorderSide(width: 0.3, color: Colors.grey))),
        child: Row(
          children: [
            Container(
              margin: const EdgeInsets.all(1),
              child: Image(
                image: AssetImage(_typeImage(item.type)),
                width: 20,
                height: 20,
              ),
            ),
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  margin: const EdgeInsets.only(left: 10),
                  child: _title(item),
                ),
                Container(
                  margin: const EdgeInsets.only(top: 5, left: 10),
                  child: (item.price == null) && (item.star == null)
                      ? null
                      : _subTitle(item),
                )
              ],
            ))
          ],
        ),
      ),
    );
  }

  _typeImage(String? type) {
    // 默认图片配置
    String imageName = 'district';

    var path = 'images/type_$imageName.png';

    if (type == null) return path;

    if (TYPES.contains(type)) {
      imageName = type;
    }
    return path;
  }

  _title(SearchItem item) {
    List<TextSpan> spans = [];
    spans.addAll(_keywordTextSpans(item.word ?? '', searchModel?.keyword));
    spans.add(TextSpan(
        text: ' ${item.districtname ?? ''}  ${item.zonename ?? ''}',
        style: const TextStyle(fontSize: 16, color: Colors.grey)));
    return RichText(text: TextSpan(children: spans));
  }

  _subTitle(SearchItem item) {
    return RichText(
        text: TextSpan(children: [
      TextSpan(
          text: item.price ?? '',
          style: const TextStyle(fontSize: 16, color: Colors.orange)),
      TextSpan(
          text: ' ${item.star ?? ''}',
          style: const TextStyle(fontSize: 16, color: Colors.grey))
    ]));
  }

  _keywordTextSpans(String? word, String? keyword) {
    List<TextSpan> spans = [];
    if (word == null || word.isEmpty || keyword == null || keyword.isEmpty) {
      return spans;
    }
    List<String> arr = word.split(keyword);
    TextStyle normalStyle =
        const TextStyle(fontSize: 16, color: Colors.black87);
    TextStyle keywordStyle =
        const TextStyle(fontSize: 16, color: Colors.orange);
    for (var i = 0; i < arr.length; i++) {
      if ((i + 1) % 2 == 0) {
        spans.add(TextSpan(text: keyword, style: keywordStyle));
      }
      // print((i + 1) % 2);
      // print(arr);
      // print(arr.length);
      String val = arr[i];
      if (val.isNotEmpty) {
        spans.add(TextSpan(text: val, style: normalStyle));
      }
    }
    return spans;
  }

  _jumpToSpeak() {
    NavigatorUtil.push(context, const SpeakPage());
  }
}
